package com.example.UDP_measure;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Set;

public class show_network extends AppCompatActivity {
    private static Charset charset= Charset.forName("utf8");
    int max=3;
    MyTask myTask;
    TextView textViewThroughput,textViewDelay,textViewPacketloss;//三个文本框
    LinearLayout linearLayout;
    DatagramChannel channel;
    Selector selector;
    String IP;
    int port;
    long time1=0,time2=0;
    Handler handler;
    double[] delay;
    double[] throughput;
    int[] packetloss;
    int times;//限制一下单次测量时长，免得它无限跑
    Context context;
    private class MyTask extends AsyncTask<Void,String,Boolean>{
        int t=0;
        protected void onPreExecute(){
            handler=new Handler(){
                @Override
                public void handleMessage(Message msg){
                    super.handleMessage(msg);
                    String temp=msg.obj+"";
                    temp=temp.substring(0,5);
                    throughput[t]=Double.parseDouble(temp);
                    packetloss[t]=msg.arg1;
                    textViewThroughput.setText(throughput[t]+"Mbs");
                    textViewPacketloss.setText(packetloss[t]+"%");
                    t++;
                }
            };
        }
        @Override
        protected Boolean doInBackground(Void... voids) {
            try {
                //虚拟连接   客户端单方面连向服务器
                InetSocketAddress as=new InetSocketAddress(IP,port);
                channel.connect(as);
                //获得当前时间
                ByteBuffer writebuffer=ByteBuffer.allocate(1024);
                ByteBuffer readbuffer=ByteBuffer.allocate(1024);
                while(times<10){
                    //计算延迟
                    if(selector.select(5)<1){
                        writebuffer.put("begin".getBytes());
                        writebuffer.flip();
                        channel.write(writebuffer);
                        time1=System.currentTimeMillis();//获取发送包时的毫秒数
                        writebuffer.clear();
                        continue;
                    }
                    Set<SelectionKey> keys = selector.selectedKeys();
                    Iterator<SelectionKey> it = keys.iterator();
                    while (it.hasNext()) {
                        SelectionKey key = it.next();
                        it.remove();
                        if (key.isReadable()) {//读到的一定是receive
                            readbuffer.clear();
                            channel.receive(readbuffer);
                            readbuffer.flip();
                            String msg = charset.decode(readbuffer).toString();
                            time2=System.currentTimeMillis();
                            delay[times]=time2-time1;//柱状图

                            //在这里建立子线程，然后把子线程中存在的吞吐量用一个static变量存起来  返回给主线程累加，，从而得到最终的吞吐量
                            Throughput[] throughput=new Throughput[max];
                            for(int i=0;i<max;++i){
                                throughput[i]=new Throughput(IP,port+1+i,null);
                                throughput[i].start();
                            }
                            for(int i=0;i<max;++i){
                                //主线程其他工作完毕,等待子线程的结束, 调用join系列的方法即可(可以设置超时时间)
                                try {
                                    throughput[i].join();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            try{
                                throughput[0]=new Throughput(null,0,handler);
                                throughput[0].start();
                                throughput[0].join();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            ++times;
                            //将延迟传递给主函数
                            publishProgress((time2-time1)+"");
                        }
                    }
/*
                    */
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        @Override
        protected void onProgressUpdate(String... progress){
            textViewDelay.setText(progress[0]+"ms");
            super.onProgressUpdate(progress);
            if(times>=10){
                //画柱状图 延迟
                int[] Y={10,20,30,40,50,60};

                Histogram histogram=new Histogram(context,"过去一段时间的网络延迟","延迟/ms",Y,delay,5);

                linearLayout=(LinearLayout)findViewById(R.id.view1);
                linearLayout.addView(histogram);

                //画柱状图 吞吐量
                int[] Y1={10,20,30,40,50,60};
                for(int i=0;i<10;++i){
                    throughput[i]=throughput[i]*10;
                }
                Histogram histogram1=new Histogram(context,"过去一段时间的网络吞吐量","吞吐量/100Kbs",Y1,throughput,5);

                linearLayout=(LinearLayout)findViewById(R.id.view2);
                linearLayout.addView(histogram1);

                //画柱状图 丢包率
                int[] Y2={5,10,15,20,25,30};
                Histogram histogram2=new Histogram(context,"过去一段时间的网络丢包率","%",Y2,packetloss,10);

                linearLayout=(LinearLayout)findViewById(R.id.view3);
                linearLayout.addView(histogram2);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.network_layout);

        //用于画柱状图
        context=this;
        times=0;
        delay=new double[10];
        Arrays.fill(delay,(double)0.0);
        throughput=new double[10];
        Arrays.fill(throughput,(double)0.0);
        packetloss=new int[10];
        Arrays.fill(packetloss,(int)0);
        textViewThroughput=(TextView)findViewById(R.id.textView2);
        textViewDelay=(TextView)findViewById(R.id.textView3);
        textViewPacketloss=(TextView)findViewById(R.id.textView7);

        //用于页面跳转以及数据传递
        Intent intent=getIntent();
        IP=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        port=Integer.parseInt(intent.getStringExtra(MainActivity.EXTRA_MESSAGE2));

        //用于接收Server的数据
        try {
            channel=DatagramChannel.open();
            channel.configureBlocking(false);
            selector=Selector.open();
            channel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }


        //启动异步线程
        myTask=new MyTask();
        myTask.execute();
    }
}